#coding=utf8
import sys, MangaBase, re, urllib2, urlparse
import cmrhelper
from cmrhelper import GbkToUtf8, UtfToGbk
class Parser(MangaBase.CMangaBase):
    "zxmh.net parser"
    def Start(self):
        self.IniRe()
        try:
            self.chaptercontent = urllib2.urlopen(self.m_url).read()
        except:
            self.m_mangalog.writeLog('get page content fail','fatal')
            return
        # if m_manganame is None,then parse manganame
        if not self.m_manganame:
            self.ParseName()
        self.GetChapters()
        if self.m_chapterlist:
            for item in self.m_chapterlist:
                self.ParseChapter(item[0], item[1])
        self.End()

    def IniRe(self):        
        self.namere = re.compile("<div class=\"fn1\"><img src=\".*?\" border=\"0\" alt=\"(.*?)\" /></div>")
        self.chapterre = re.compile('<div class=\"fn3c\"><a href=\"(.*?)\" target="_blank" title="">(.*?)</a></div>')
        self.picre = re.compile(r"<a href=\".*?\"><img src=\"(.*?)\" border=\"0\" /></a>")

    def ParseName(self):
        "get manga name if name is None"
        self.m_mangalog.writeLog('get manga name')
        if self.namere.findall(self.chaptercontent):
            self.m_manganame = GbkToUtf8(self.namere.findall(self.chaptercontent)[0])
            self.m_mangalog.writeLog('get manga name success, manga name [%s]' %
                                     self.m_manganame)

    def ParseChapter(self, curl, title):
        "parse each chapter to generate url of pictures"
        try:
            content = urllib2.urlopen(curl).read()
            pagenum = self.getpagenum(content)
            pageurl = self.pagegenerate(curl,content,pagenum)
            for i in range(0,len(pageurl)):
                content = urllib2.urlopen(pageurl[i]).read()
                item = self.parserpic(content).replace('&amp;','&')
                if item:
                    self.PushPic([item, pageurl[i], title, self.m_manganame])
        except  Exception, e:
            self.m_mangalog.writeLog(str(e) + ' in ParseChapter', 'error')
    
    def GetChapters(self):
        "get manga chapters"
        try:
            if self.chapterre.findall(self.chaptercontent):
                for item in self.chapterre.findall(self.chaptercontent):
                    self.m_chapterlist.append([GbkToUtf8(urlparse.urljoin(self.m_url, item[0])),\
                                                   GbkToUtf8(item[1])])
                    self.m_chaptercnt += 1
            self.m_mangalog.writeLog('get chapters finish total: [%d] chapters'\
                                         % self.m_chaptercnt)
        except  Exception, e:
            self.m_mangalog.writeLog(str(e)+' in getchapter','error')

    def getpagenum(self, content):
        "get the chapters pagenum"
        '''第(1/17)页 跳转到第'''
        numre = re.compile(UtfToGbk("第\(1/(\d*?)\)页 跳转到第"))
        if numre.findall(content):
            return int(numre.findall(content)[0])
        else:
            return 0

    def pagegenerate(self, url,content,pagenum):
        pageurl = []
        pageurl.append(url)
        if pagenum:
            urlhead = url[0:-2]
            urltail = '/'
            for i in range(2,pagenum):
                pageurl.append(urlhead+str(i)+urltail)
        return pageurl

    def parserpic(self, attrs):
        result = self.picre.findall(attrs)
        if result:
            return result[0]
        else:
            return None
